<script setup lang="ts">
import { ElTree } from 'element-plus'
import type { Tree } from './type'
import { pointApi } from '@/api'

const { vLoading, withLoading } = useDefineLoading()

const filterTextInput = ref<string>('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = shallowRef<any[]>([])

const emitter = inject<any>('model-configs:emitter')

watch(
  () => filterTextInput.value,
  (val: string) => {
    treeRef.value?.filter?.(val)
  },
)

function filterNode(value: string, data: Tree) {
  if (!value)
    return true
  return data.pointName.includes(value)
}

function clickNode(data: Tree) {
  emitter?.emit('query:point-indicators', data)
}

async function getTreeData() {
  const { data } = await withLoading(pointApi.loadTreePoint)()
  treeData.value = data || []
}

onMounted(() => {
  getTreeData()
})
</script>

<template>
  <div v-loading class="view-tree height-fill box-border">
    <h5
      class="flex-incompressible margin-0 align-center flex justify-between"
    >
      <span>用能单元（点位）</span>
    </h5>
    <ElInput
      v-model="filterTextInput"
      placeholder="关键字"
      class="flex-incompressible"
    />
    <BScrollbar>
      <ElTree
        ref="treeRef"
        class="flex-fillRemaining"
        :data="treeData"
        :props="{
          label: 'pointName',
          children: 'children',
        }"
        node-key="id"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @contextmenu.prevent
        @node-click="clickNode"
      />
    </BScrollbar>
  </div>
</template>
